package com.yonyou.ucf.mdf.app.vehicle.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.yonyou.ucf.mdf.app.vehicle.common.BaseResult;
import com.yonyou.ucf.mdf.app.vehicle.common.UUIDGenerator;
import com.yonyou.ucf.mdf.app.vehicle.exceptions.ServiceException;
import com.yonyou.ucf.mdf.app.vehicle.model.UrbanepWechatConfig;
import com.yonyou.ucf.mdf.app.vehicle.model.UrbanepWechatMessagePush;
import com.yonyou.ucf.mdf.app.vehicle.service.IWxMessageSendService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;

/**
 * 微信公众号消息推送 业务层处理
 * 
 * @author smartpark
 */
@Slf4j
@Service
public class WxMessageSendServiceImpl implements IWxMessageSendService {

//    @Autowired
//    private UrbanepWechatConfigMapper whechatConfigMapper;
//
//    @Autowired
//    private UrbanepWechatMessagePushMapper wechatMessagePushMapper;


    /**
     * 公众号消息推送
     * @param eventId
     * @param wechatOpenid
     * @param pushType
     * @param page
     * @return
     */
    @Override
    public BaseResult messagePush(String eventId, String wechatOpenid, String pushType, String page) {
        BaseResult baseResult = new BaseResult();
        try {
//            RestTemplate restTemplate = new RestTemplate();
//            String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/bizsend?access_token=" + getAccessToken();
//
//            if(StringUtils.isBlank(page)) {
//                page = ""; // 跳转网页时填写
//            }
//
//            JSONObject data = new JSONObject();
//            JSONObject jsonObject = new JSONObject();
//
//            if(pushType.equals("toBePaid")) { // 订单待支付提醒
////                data = toBePaidMessage(orderSubId);
//                jsonObject.put("template_id", ""); // 所需下发的订阅模板id
//                jsonObject.put("page", page);
//            } else if(pushType.equals("couponExpire")) { // 优惠即将到期提醒
////                data = couponExpireMessage(passengerCouponId);
//                jsonObject.put("template_id", ""); // 所需下发的订阅模板id
//                jsonObject.put("page", page);
//            } else if(pushType.equals("getCoupon")) { // 优惠到账通知
////                data = couponReceiptMessage(passengerCouponId);
//                jsonObject.put("template_id", ""); // 所需下发的订阅模板id
//                jsonObject.put("page", page);
//            }
//            log.info("公众号消息推送 data={}", data);
//            if(!data.isEmpty()) {
//                jsonObject.put("touser", wechatOpenid); // 接收者（用户）的 openid
//                jsonObject.put("data", data);
//
//                // page 和 miniprogram 同时不填，无跳转；page 和 miniprogram 同时填写，优先跳转小程序；
//                jsonObject.put("miniprogram", data); // 跳转小程序时填写，格式如{ "appid": "pagepath": { "value": 页面路径 } }
//
//                ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, jsonObject, String.class);
//                String body = responseEntity.getBody();
//                JSONObject object = JSON.parseObject(body);
//
//                log.info("公众号消息推送：{}", object);
//                if(!object.getString("errmsg").equals("ok")) {
//                    baseResult.setCode("-1");
//                    baseResult.setSuccess(false);
//                    baseResult.setMsg(object.getString("errmsg"));
//                } else {
//                    UrbanepWechatMessagePush msgPush = new UrbanepWechatMessagePush();
//                    msgPush.setPushId(UUIDGenerator.nextId());
//                    msgPush.setEventId(eventId);
//                    msgPush.setTouserId();
//                    msgPush.setWechatOpenid(wechatOpenid);
//                    msgPush.setPushType("offiaccount");
//                    msgPush.setPushMessage(jsonObject.toString());
//                    msgPush.setPushTime(new Date());
//                    wechatMessagePushMapper.insertSelective(msgPush);
//                }
//            }
        } catch (Exception e) {
            log.error("公众号消息推送异常：{}", e.getMessage(), e);
            throw new ServiceException("-1", "公众号消息推送异常");
        }
        return baseResult;
    }

    /**
     * 微信小程序消息推送
     * @param eventId
     * @param wechatOpenid
     * @param pushType
     * @param page
     * @return
     */
    @Override
    public BaseResult appletMessagePush(String eventId, String wechatOpenid, String pushType, String page) {
        BaseResult baseResult = new BaseResult();
        try {
//            RestTemplate restTemplate = new RestTemplate();
//            String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken();
//
//            if(StringUtils.isBlank(page)) {
//                page = "pages/home/home";
//            }
//
//            JSONObject data = new JSONObject();
//            JSONObject jsonObject = new JSONObject();
//
//            if(pushType.equals("toBePaid")) { // 订单待支付提醒
////                data = toBePaidMessage(orderSubId);
//                jsonObject.put("template_id", "");
//                jsonObject.put("page", page);
//            } else if(pushType.equals("couponExpire")) { // 优惠即将到期提醒
////                data = couponExpireMessage(passengerCouponId);
//                jsonObject.put("template_id", "");
//                jsonObject.put("page", page);
//            } else if(pushType.equals("getCoupon")) { // 优惠到账通知
////                data = couponReceiptMessage(passengerCouponId);
//                jsonObject.put("template_id", "");
//                jsonObject.put("page", page);
//            }
//            log.info("小程序消息推送 data={}", data);
//            if(!data.isEmpty()) {
//                jsonObject.put("touser", wechatOpenid);
//                jsonObject.put("data", data);
//
//                ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, jsonObject, String.class);
//                String body = responseEntity.getBody();
//                JSONObject object = JSON.parseObject(body);
//
//                log.info("小程序消息推送：{}", object);
//                if(!object.getString("errmsg").equals("ok")) {
//                    baseResult.setCode("-1");
//                    baseResult.setSuccess(false);
//                    baseResult.setMsg(object.getString("errmsg"));
//                } else {
//                    UrbanepWechatMessagePush msgPush = new UrbanepWechatMessagePush();
//                    msgPush.setPushId(UUIDGenerator.nextId());
//                    msgPush.setEventId(eventId);
//                    msgPush.setTouserId();
//                    msgPush.setWechatOpenid(wechatOpenid);
//                    msgPush.setPushType("applet");
//                    msgPush.setPushMessage(jsonObject.toString());
//                    msgPush.setPushTime(new Date());
//                    wechatMessagePushMapper.insertSelective(msgPush);
//                }
//            }
        } catch (Exception e) {
            log.error("小程序消息推送异常：{}", e.getMessage(), e);
            throw new ServiceException("-1", "小程序消息推送异常");
        }
        return baseResult;
    }

//    private String getAccessToken() {
//        UrbanepWechatConfig config = whechatConfigMapper.selectByPrimaryKey("wechat_config_1");
//        if(config == null) {
//            throw new ServiceException("-1", "微信config信息不存在");
//        }
//        return config.getAccesstoken();
//    }

}
